package com.crawler.gmail.utils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.UUID;

/**
 * <描述>
 * <详细介绍>
 *
 * @author 王明明
 * @since wiki
 */
public class OssFile {

        public static OSSClient ossClient = new OSSClient( "http://oss-cn-beijing.aliyuncs.com","LTAI5tLxDFPoWfkFsX765L98","FIhkterS9k68mRzQXSOBpLiCWIcHlQ");
//    public static OSSClient ossClient = new OSSClient("http://oss-cn-beijing.aliyuncs.com", "LTAI5vuLTstCvjIp", "0dvetxsB3koHv8aTnvJeMXVfNZIasd");
    private static String path = "local";

    public static String uploadFile(String content) throws IOException {
        File tempFile = File.createTempFile("tmp_", ".html");
        FileWriter fileWriter = new FileWriter(tempFile);
        fileWriter.write(content);
        fileWriter.flush();
        fileWriter.close();
        String fileKey = generateFileKey();
        PutObjectRequest putObjectRequest = new PutObjectRequest("xrxs-spider", fileKey, tempFile);
//        PutObjectRequest putObjectRequest = new PutObjectRequest("xinzhao", fileKey, tempFile);
        PutObjectResult pubObjectRes = ossClient.putObject(putObjectRequest);
        return fileKey;
    }

    public static String uploadFile(File file) throws IOException {
        String fileKey = generateFileKey();
        PutObjectRequest putObjectRequest = new PutObjectRequest("xrxs-spider", fileKey, file);
//        PutObjectRequest putObjectRequest = new PutObjectRequest("xinzhao", fileKey, file);
        PutObjectResult pubObjectRes = ossClient.putObject(putObjectRequest);
        return fileKey;
    }

    public static String generateFileKey() {
        Calendar calendar = new GregorianCalendar();
        Integer year = calendar.get(Calendar.YEAR);
        Integer month = calendar.get(Calendar.MONTH) + 1;
        return path + "/" + year + "/" + month + "/" + UUID.randomUUID().toString().replace("-", "");
    }

    public static void downFile() throws IOException {
        GetObjectRequest request = new GetObjectRequest("xinzhao", "local/2021/11/8af094b6bf504bf4b00af5c167f6e0b1");
        File file = File.createTempFile("oss_", "txt");
        ossClient.getObject(request, file);
        System.out.println(file);
    }

    public static void main(String[] args) throws IOException {
//        System.out.println(uploadFile("asdasdasdas"));
        downFile();
    }

}
